<?php


namespace App\Http\Controllers\Admin;


use App\Model\Goods;
use App\Model\Snapped;
use App\Model\SnappedSku;
use App\Tool\Enum;
use App\Tool\Json;
use Illuminate\Support\Facades\Redis;

//use Illuminate\Support\Facades\DB;


class SnappedController extends AuthCheckController
{

    /**
     * 商品搜索
     * Create by PeterYang
     * 2020/06/02 21:21:24
     * Email:904801074@qq.com
     * @return false|string
     */
    function getGoodsList()
    {

        $list = Goods::with('goods_sku.goods_sku_detail')->orderBy('id', 'desc');


        $this->getSearch('name', function ($name) use ($list) {


            $list->where('name', 'like', '%' . $name . '%');

        });


        return Json::code(1, 'success', paginate($list, request()->input('p')));

    }

    /**
     * 获取参数
     * Create by PeterYang
     * 2020/05/31 17:46:16
     * Email:904801074@qq.com
     * @param $name
     * @param $callback
     */
    private function getSearch($name, $callback)
    {

        $name = request()->input($name);

        if ($name) {

            $callback($name);

        }

    }

    /**
     * 新增秒杀
     * Create by Peter
     * 2020/06/03 16:32:08
     * Email:904801074@qq.com
     * @return false|string
     * @throws \Exception
     */
    function snappedSave()
    {

        try {

            \DB::beginTransaction();

            Redis::multi();

            $post = request()->post();

            $id = request()->input('id');

            $snapped_id = 0;

            $data = [
                'goods_id' => $post['goods_id'],
                'cycle' => Enum::range($post['cycle'], [1, 2, 3, 4]),
                'start_time' => $post['start_time'],
                'end_time' => $post['end_time'],
                'every_day_start_time' => $post['every_day_start_time'],
                'every_day_end_time' => $post['every_day_end_time'],
                'week_time' => $post['week_time'],
                'date_time' => $post['date_time']
            ];


            if ($id) {

                Snapped::find($id)->fill($data)->save();

                SnappedSku::where('snapped_id', $id)->delete();

                $snapped_id = $id;

            } else {

                $snapped = Snapped::create($data);

                $snapped_id = $snapped->id;

            }


            foreach ($post['sku_list'] as $key => $value) {


                SnappedSku::create([

                    'snapped_id' => $snapped_id,
                    'type' => $value['type'],
                    'price' => $value['price'],
                    'percent' => $value['percent'],
                    'sku_id' => $value['sku_id'],
                    'goods_id' => $post['goods_id']
                ]);

                $num = (int)$value['num'];

                if ($num <= 0) throw new \Exception('库存设置不能小于等于0');

                //剩余库存
                Redis::set('snapped:num_goods_sku_id_' . $value['sku_id'], $num);

                //写入时的库存（用于进度条）
                Redis::set('snapped:all_goods_sku_id_' . $value['sku_id'], $num);

            }


            \DB::commit();

            Redis::exec();

            return Json::code(1, 'success', $post);

        } catch (\Exception $exception) {

            \DB::rollBack();

            Redis::discard();

            $code = explode(':', $exception->getMessage())[0];


            if ($code == 'SQLSTATE[23000]') {

                return Json::code(2, '一个商品只能有一个秒杀活动');

            }

            return Json::code(2, $exception->getMessage());

        }

    }

    /**
     * Create by Peter
     * 2020/07/06 15:07:00
     * Email:904801074@qq.com
     * @return false|string
     */
    function snappedDelete()
    {

        try {

            \DB::beginTransaction();

            $id = request()->input('id');

            $id = (int)$id;

            foreach (SnappedSku::where('snapped_id', $id)->get() as $key => $value) {


                $value->delete();

            }


            Snapped::destroy($id);


            \DB::commit();


            return Json::code(1, 'success');

        } catch (\Exception $exception) {

            \DB::rollBack();

            \Log::debug($exception->getMessage());

            return Json::code(2, '');


        }


    }


    /**
     * 秒杀禁用
     * Create by Peter
     * 2020/07/06 17:21:45
     * Email:904801074@qq.com
     * @return false|string
     */
    function snappedDisable()
    {


        try {

            \DB::beginTransaction();

            $id = request()->input('id');

            $id = (int)$id;

            foreach (SnappedSku::where('snapped_id', $id)->get() as $key => $value) {


                $value->disable = 2;

                $value->save();

            }


            Snapped::find($id)->fill(['disable' => 2])->save();

            \DB::commit();

            return Json::code(1, 'success');

        } catch (\Exception $exception) {


            \DB::rollBack();

            \Log::debug($exception->getMessage());

            return Json::code(2, '');

        }


    }


    /**
     * 秒杀激活
     * Create by Peter
     * 2020/07/06 17:21:55
     * Email:904801074@qq.com
     */
    function snappedActive()
    {

        try {

            \DB::beginTransaction();

            $id = request()->input('id');

            $id = (int)$id;

            foreach (SnappedSku::where('snapped_id',$id)->get() as $key=>$value){


                $value->disable=1;

                $value->save();

            }


            Snapped::find($id)->fill(['disable'=>1])->save();

            \DB::commit();

            return Json::code(1, 'success');

        }catch (\Exception $exception){


            \DB::rollBack();

            \Log::debug($exception->getMessage());

            return Json::code(2,'');

        }


    }


    /**
     * 秒杀列表
     * Create by PeterYang
     * 2020/06/03 19:49:24
     * Email:904801074@qq.com
     * @return false|string
     */
    function snappedList()
    {


        $list = Snapped::with('goods')->orderBy('id', 'desc');


        return Json::code(1, 'success', paginate($list, request()->input('p', 1)));

    }

    /**
     * Create by PeterYang
     * 2020/06/06 14:47:34
     * Email:904801074@qq.com
     * @return false|string
     */
    function detail()
    {

        $id = request()->input('id');

        $data = Snapped::with('snapped_sku')->with('goods.goods_sku.goods_sku_detail')->find($id);

        $goods_sku = optional($data->goods)->goods_sku;

        $data['goods_sku'] = $goods_sku;

        $snapped_sku = $data->snapped_sku;

        if ($snapped_sku) $snapped_sku = $snapped_sku->toArray();

        $data['sku_list'] = $snapped_sku;

        $checkList = array_column($snapped_sku, 'sku_id');

        if ($checkList) $data['checkList'] = $checkList;

        return Json::code(1, 'code', $data);
    }


}
